import React, { useState, useEffect } from 'react';
import { 
  Paper, 
  Grid, 
  Typography, 
  Box, 
  Tabs, 
  Tab, 
  Table, 
  TableBody, 
  TableCell, 
  TableContainer, 
  TableHead, 
  TableRow, 
  Button,
  TextField,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  Alert,
  MenuItem,
  Select,
  FormControl,
  InputLabel,
  Chip,
  IconButton,
  Tooltip,
  Snackbar,
  CircularProgress,
  Divider,
  Card,
  CardContent,
  CardActions
} from '@mui/material';
import { 
  Search, 
  Block, 
  CheckCircle, 
  Person, 
  Movie, 
  Settings, 
  Warning, 
  Delete, 
  Announcement,
  Flag,
  AddCircle,
  Store,
  LocalOffer,
  List
} from '@mui/icons-material';

// 导入API函数
import { 
  getUsers, 
  banUser, 
  unbanUser, 
  getActivePromotions,
  createPromotion,
  closePromotion,
  processReport,
  getPendingReports,
  publishNotice,
  getAllNotices,
  deleteNotice,
  getPendingTorrents,
  reviewTorrent,
  getAllProducts,
  addProduct,
  updateProduct,
  deleteProduct,
  configureSystemParam,
  getSystemParam
} from '../api/admin';
import { getSeedList } from '../api/seed';
import { instance } from '../axios';

function Admin() {
  const [tabValue, setTabValue] = useState(0);
  const [openDialog, setOpenDialog] = useState(false);
  const [dialogType, setDialogType] = useState('');
  const [selectedItem, setSelectedItem] = useState(null);
  const [searchTerm, setSearchTerm] = useState('');
  const [banReason, setBanReason] = useState('');
  const [banTime, setBanTime] = useState(0); // 封禁时间，0表示永久封禁
  const [snackbarOpen, setSnackbarOpen] = useState(false);
  const [snackbarMessage, setSnackbarMessage] = useState('');
  const [snackbarSeverity, setSnackbarSeverity] = useState('success');
  
  // 用户管理状态
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  
  // 种子管理状态
  const [pendingTorrents, setPendingTorrents] = useState([]);
  const [torrentLoading, setTorrentLoading] = useState(true);
  const [reviewReason, setReviewReason] = useState('');
  
  // 促销活动状态
  const [promotions, setPromotions] = useState([]);
  const [startDate, setStartDate] = useState('');
  const [endDate, setEndDate] = useState('');
  const [selectedTorrentId, setSelectedTorrentId] = useState('');
  
  // 举报管理状态
  const [reports, setReports] = useState([]);
  const [processResult, setProcessResult] = useState('');
  const [actionTaken, setActionTaken] = useState(0);
  
  // 通知管理状态
  const [notices, setNotices] = useState([]);
  const [noticeTopic, setNoticeTopic] = useState('');
  const [noticeContent, setNoticeContent] = useState('');

  // 商店管理状态
  const [products, setProducts] = useState([]);
  const [productName, setProductName] = useState('');
  const [productDesc, setProductDesc] = useState('');
  const [productPrice, setProductPrice] = useState(0);
  const [productType, setProductType] = useState('');
  const [productDuration, setProductDuration] = useState(0);
  const [productStock, setProductStock] = useState(-1);

  // 系统配置状态
  const [configKey, setConfigKey] = useState('');
  const [configValue, setConfigValue] = useState('');
  const [systemParams, setSystemParams] = useState({});

  // 种子列表状态
  const [allTorrents, setAllTorrents] = useState([]);
  const [allTorrentsLoading, setAllTorrentsLoading] = useState(true);
  const [sortField, setSortField] = useState(''); // 添加排序字段状态
  const [sortDirection, setSortDirection] = useState('asc'); // 添加排序方向状态

  // 在初始化时添加默认价格参数（如果后端没有返回的话）
  useEffect(() => {
    if (Object.keys(systemParams).length > 0 && !systemParams.hasOwnProperty('defaultPrice')) {
      handleAddDefaultPrice();
    }
  }, [systemParams]);

  // 添加默认价格参数
  const handleAddDefaultPrice = async () => {
    try {
      await configureSystemParam('defaultPrice', '10');
      showSnackbarMessage('默认价格参数添加成功');
      fetchSystemParams();
    } catch (error) {
      console.error('添加默认价格参数失败:', error);
      showSnackbarMessage('添加默认价格参数失败', 'error');
    }
  };

  // 获取所有数据
  useEffect(() => {
    fetchUsers();
    fetchPendingTorrents();
    fetchActivePromotions();
    fetchNotices();
    fetchProducts();
    fetchAllTorrents();
    fetchPendingReports();
    fetchSystemParams();
  }, []);

  const fetchUsers = async () => {
    try {
      setLoading(true);
      console.log('开始获取用户列表...');
      const response = await getUsers();
      console.log('获取用户列表成功:', response);
      setUsers(response || []);
      setLoading(false);
    } catch (error) {
      console.error('获取用户列表失败:', error);
      console.error('错误详情:', error.response?.data || error.message);
      showSnackbarMessage('获取用户列表失败', 'error');
      setUsers([]);
      setLoading(false);
    }
  };

  const fetchPendingTorrents = async () => {
    try {
      setTorrentLoading(true);
      console.log('开始获取待审核种子...');
      const response = await getPendingTorrents();
      console.log('获取待审核种子成功:', response);
      setPendingTorrents(response || []);
      setTorrentLoading(false);
    } catch (error) {
      console.error('获取待审核种子失败:', error);
      console.error('错误详情:', error.response?.data || error.message);
      showSnackbarMessage('获取待审核种子失败', 'error');
      setPendingTorrents([]);
      setTorrentLoading(false);
    }
  };

  const fetchActivePromotions = async () => {
    try {
      console.log('开始获取促销活动...');
      const response = await getActivePromotions();
      console.log('获取促销活动成功:', response);
      setPromotions(response || []);
    } catch (error) {
      console.error('获取促销活动失败:', error);
      console.error('错误详情:', error.response?.data || error.message);
      showSnackbarMessage('获取促销活动失败', 'error');
      setPromotions([]);
    }
  };

  const fetchNotices = async () => {
    try {
      console.log('开始获取通知列表...');
      const response = await getAllNotices();
      console.log('获取通知列表成功:', response);
      setNotices(response || []);
    } catch (error) {
      console.error('获取通知列表失败:', error);
      console.error('错误详情:', error.response?.data || error.message);
      showSnackbarMessage('获取通知列表失败', 'error');
      setNotices([]);
    }
  };

  const fetchProducts = async () => {
    try {
      console.log('开始获取商品列表...');
      const response = await getAllProducts();
      console.log('获取商品列表成功:', response.data);
      setProducts(response.data.products || []);
    } catch (error) {
      console.error('获取商品列表失败:', error);
      console.error('错误详情:', error.response?.data || error.message);
      showSnackbarMessage('获取商品列表失败', 'error');
      setProducts([]);
    }
  };

  const fetchPendingReports = async () => {
    try {
      console.log('开始获取待处理举报...');
      const response = await getPendingReports();
      console.log('获取待处理举报成功:', response);
      setReports(response || []);
    } catch (error) {
      console.error('获取待处理举报失败:', error);
      console.error('错误详情:', error.response?.data || error.message);
      showSnackbarMessage('获取待处理举报失败', 'error');
      setReports([]);
    }
  };

  const fetchAllTorrents = async () => {
    try {
      setAllTorrentsLoading(true);
      console.log('开始获取所有种子列表...');
      const response = await getSeedList();
      console.log('获取所有种子列表成功:', response);
      setAllTorrents(response || []);
      setAllTorrentsLoading(false);
    } catch (error) {
      console.error('获取所有种子列表失败:', error);
      console.error('错误详情:', error.response?.data || error.message);
      showSnackbarMessage('获取所有种子列表失败', 'error');
      setAllTorrents([]);
      setAllTorrentsLoading(false);
    }
  };

  const fetchSystemParams = async () => {
    try {
      console.log('开始获取系统参数...');
      const response = await getSystemParam();
      console.log('获取系统参数成功:', response);
      
      if (response && Array.isArray(response)) {
        // 将数组转换为对象，方便按键名访问
        const paramsObj = {};
        response.forEach(param => {
          if (param && param.configKey && param.configValue !== undefined) {
            paramsObj[param.configKey] = param.configValue;
          }
        });
        setSystemParams(paramsObj);
      }
    } catch (error) {
      console.error('获取系统参数失败:', error);
      console.error('错误详情:', error.response?.data || error.message);
      showSnackbarMessage('获取系统参数失败', 'error');
    }
  };

  const handleTabChange = (event, newValue) => {
    setTabValue(newValue);
  };

  const handleOpenDialog = (type, item) => {
    setDialogType(type);
    setSelectedItem(item);
    setBanReason('');
    setBanTime(0);
    setReviewReason('');
    setProcessResult('');
    setActionTaken(0);
    setNoticeTopic('');
    setNoticeContent('');
    setProductName('');
    setProductDesc('');
    setProductPrice(0);
    setProductType('');
    setProductDuration(0);
    setProductStock(-1);

    // 如果是编辑系统参数，预填表单
    if (type === 'configSystem' && item) {
      setConfigKey(item.key);
      setConfigValue(item.value);
    }
    
    // 如果是编辑商品，预填表单
    if (type === 'editProduct' && item) {
      setProductName(item.name || '');
      setProductDesc(item.description || '');
      setProductPrice(item.price || 0);
      setProductType(item.type || '');
      setProductDuration(item.duration || 0);
      setProductStock(item.stock || -1);
    }

    // 如果是创建促销活动，预填种子ID
    if (type === 'createPromotion' && item) {
      setSelectedTorrentId(item.id || '');
    }

    if (type === 'ban' && item) {
      setBanReason(item.banReason || '');
    }
    if (type === 'unban' && item) {
      setBanReason(item.banReason || '');
    }

    setOpenDialog(true);
  };

  const handleCloseDialog = () => {
    setOpenDialog(false);
    setSelectedItem(null);
  };

  const handleAction = async () => {
    try {
      switch (dialogType) {
        case 'ban':
          await banUser(selectedItem.id, banReason, banTime);
          showSnackbarMessage(`已封禁用户 ${selectedItem.username}${banTime > 0 ? ` ${banTime}天` : ' (永久)'}`);
          fetchUsers();
          break;
        case 'unban':
          await unbanUser(selectedItem.id);
          showSnackbarMessage(`已解封用户 ${selectedItem.username}`);
          fetchUsers();
          break;
        case 'approve':
          await reviewTorrent(selectedItem.id, 1); // 1 表示通过
          showSnackbarMessage(`已通过种子 ${selectedItem.fileName || selectedItem.name}`);
          fetchPendingTorrents();
          break;
        case 'reject':
          await reviewTorrent(selectedItem.id, 2, reviewReason); // 2 表示拒绝
          showSnackbarMessage(`已拒绝种子 ${selectedItem.fileName || selectedItem.name}`);
          fetchPendingTorrents();
          break;
        case 'createPromotion':
          if (!startDate || !endDate) {
            showSnackbarMessage('请填写完整时间信息', 'error');
            return;
          }
          await createPromotion(selectedItem.id, startDate, endDate);
          showSnackbarMessage(`已为种子 ${selectedItem.fileName || selectedItem.name} 创建促销活动`);
          fetchActivePromotions();
          break;
        case 'closePromotion':
          await closePromotion(selectedItem.id);
          showSnackbarMessage('已关闭促销活动');
          fetchActivePromotions();
          break;
        case 'createNotice':
          if (!noticeTopic || !noticeContent) {
            showSnackbarMessage('请填写完整通知信息', 'error');
            return;
          }
          const userInfo = JSON.parse(localStorage.getItem('user') || '{}');
          console.log('发布通知 - 用户信息:', userInfo);

          // 确保获取正确的管理员ID
          const adminId = userInfo;
          console.log(adminId);
          if (!adminId) {
            console.error('无法获取管理员ID，用户信息:', userInfo);
            showSnackbarMessage('无法获取管理员ID，请重新登录', 'error');
            return;
          }

          console.log('发布通知 - 参数:', { adminId, topic: noticeTopic, content: noticeContent });
          try {
            const response = await publishNotice(adminId, noticeTopic, noticeContent);
            console.log('发布通知 - 成功:', response);
            showSnackbarMessage('已发布通知');
            fetchNotices();
          } catch (error) {
            console.error('发布通知 - 失败:', error);
            console.error('错误详情:', error.response?.data || error.message);
            showSnackbarMessage(`发布通知失败: ${error.response?.data?.message || error.message}`, 'error');
            throw error; // 重新抛出错误，让外层catch捕获
          }
          break;
        case 'deleteNotice':
          await deleteNotice(selectedItem.id);
          showSnackbarMessage('已删除通知');
          fetchNotices();
          break;
        case 'addProduct':
          if (!productName || !productType || productPrice <= 0) {
            showSnackbarMessage('请填写必要的商品信息', 'error');
            return;
          }
          await addProduct(productName, productDesc, productPrice, productType, productDuration, productStock);
          showSnackbarMessage('商品添加成功');
          fetchProducts();
          break;
        case 'editProduct':
          await updateProduct(
            selectedItem.id,
            productName,
            productDesc,
            productPrice,
            productType,
            productDuration,
            productStock
          );
          showSnackbarMessage('商品更新成功');
          fetchProducts();
          break;
        case 'deleteProduct':
          await deleteProduct(selectedItem.id);
          showSnackbarMessage('商品删除成功');
          fetchProducts();
          break;
        case 'configSystem':
          if (!configKey || configValue === undefined) {
            showSnackbarMessage('请填写完整配置信息', 'error');
            return;
          }
          await configureSystemParam(configKey, configValue);
          showSnackbarMessage('系统参数配置成功');
          // 重新获取系统参数
          fetchSystemParams();
          break;
        case 'processReport':
          if (!processResult) {
            showSnackbarMessage('请填写处理结果', 'error');
            return;
          }
          await processReport(selectedItem.id, processResult, actionTaken);
          showSnackbarMessage('举报已处理');
          fetchPendingReports();
          break;
        default:
          break;
      }
      handleCloseDialog();
    } catch (error) {
      console.error('操作失败:', error);
      showSnackbarMessage(`操作失败: ${error.response?.data?.message || error.message}`, 'error');
    }
  };

  const showSnackbarMessage = (message, severity = 'success') => {
    setSnackbarMessage(message);
    setSnackbarSeverity(severity);
    setSnackbarOpen(true);
  };

  const handleSnackbarClose = () => {
    setSnackbarOpen(false);
  };

  const handleSearchChange = (e) => {
    setSearchTerm(e.target.value);
  };

  // 状态显示样式
  const getStatusColor = (status) => {
    switch (status) {
      case 'active':
      case '正常':
      case 1:
        return 'success';
      case 'banned':
      case '封禁':
      case 0:
        return 'error';
      case 'pending':
      case '待审核':
      case 2:
        return 'warning';
      default:
        return 'default';
    }
  };

  const getStatusText = (status) => {
    switch (status) {
      case 'active':
      case 1:
        return '正常';
      case 'banned':
      case 0:
        return '封禁';
      case 'pending':
      case 2:
        return '待审核';
      default:
        return '未知';
    }
  };

  // 添加排序处理函数
  const handleSort = (field) => {
    if (sortField === field) {
      // 如果点击的是当前排序字段，则切换排序方向
      setSortDirection(sortDirection === 'asc' ? 'desc' : 'asc');
    } else {
      // 如果点击的是新的排序字段，则设置新的排序字段并默认升序
      setSortField(field);
      setSortDirection('asc');
    }
  };

  // 添加排序后的种子列表
  const getSortedTorrents = () => {
    if (!sortField) return allTorrents;

    return [...allTorrents].sort((a, b) => {
      let valueA, valueB;

      if (sortField === 'fileSize') {
        valueA = a.fileSize || 0;
        valueB = b.fileSize || 0;
      } else if (sortField === 'downloads') {
        valueA = a.downloads || 0;
        valueB = b.downloads || 0;
      }

      if (sortDirection === 'asc') {
        return valueA - valueB;
      } else {
        return valueB - valueA;
      }
    });
  };

  // 用户管理视图
  const renderUserManagement = () => (
    <Box>
      <Box sx={{ mb: 2, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <Typography variant="h6" sx={{ color: '#8e24aa', fontWeight: 'bold' }}>
          <Person sx={{ mr: 1, verticalAlign: 'middle' }} />
          用户管理
        </Typography>
        <TextField
          placeholder="搜索用户..."
          variant="outlined"
          size="small"
          value={searchTerm}
          onChange={handleSearchChange}
          InputProps={{
            startAdornment: <Search sx={{ color: 'action.active', mr: 1 }} />,
          }}
          sx={{ width: 300 }}
        />
      </Box>

      {loading ? (
        <Box sx={{ display: 'flex', justifyContent: 'center', p: 3 }}>
          <CircularProgress sx={{ color: '#d81b60' }} />
        </Box>
      ) : !users || users.length === 0 ? (
        <Alert severity="info">暂无用户数据</Alert>
      ) : (
        <TableContainer component={Paper} sx={{
          borderRadius: 2,
          boxShadow: '0 4px 6px rgba(0,0,0,0.1)',
          overflow: 'hidden'
        }}>
          <Table sx={{ minWidth: 650 }}>
            <TableHead sx={{ backgroundColor: '#fce4ec' }}>
              <TableRow>
                <TableCell>ID</TableCell>
                <TableCell>用户名</TableCell>
                <TableCell>邮箱</TableCell>
                <TableCell>操作</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {users && users
                .filter(user =>
                  user.username?.toLowerCase().includes(searchTerm.toLowerCase()) ||
                  user.email?.toLowerCase().includes(searchTerm.toLowerCase()) ||
                  user.id?.toString().includes(searchTerm)
                )
                .map((user) => (
                  <TableRow key={user.id} hover>
                    <TableCell>{user.id}</TableCell>
                    <TableCell>{user.username}</TableCell>
                    <TableCell>{user.email}</TableCell>
                    <TableCell>
                      {user.banned === false ? (
                        <Button
                          variant="outlined"
                          color="error"
                          size="small"
                          startIcon={<Block />}
                          onClick={() => handleOpenDialog('ban', user)}
                          sx={{ borderRadius: 4 }}
                        >
                          封禁
                        </Button>
                      ) : (
                        <Button
                          variant="outlined"
                          color="success"
                          size="small"
                          startIcon={<CheckCircle />}
                          onClick={() => handleOpenDialog('unban', user)}
                          sx={{ borderRadius: 4 }}
                        >
                          解封
                        </Button>
                      )}
                    </TableCell>
                  </TableRow>
                ))}
            </TableBody>
          </Table>
        </TableContainer>
      )}
    </Box>
  );

  // 种子审核视图
  const renderTorrentReview = () => (
    <Box>
      <Box sx={{ mb: 2, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <Typography variant="h6" sx={{ color: '#8e24aa', fontWeight: 'bold' }}>
          <Movie sx={{ mr: 1, verticalAlign: 'middle' }} />
          种子审核
        </Typography>
        <TextField
          placeholder="搜索种子..."
          variant="outlined"
          size="small"
          value={searchTerm}
          onChange={handleSearchChange}
          InputProps={{
            startAdornment: <Search sx={{ color: 'action.active', mr: 1 }} />,
          }}
          sx={{ width: 300 }}
        />
      </Box>

      {torrentLoading ? (
        <Box sx={{ display: 'flex', justifyContent: 'center', p: 3 }}>
          <CircularProgress sx={{ color: '#d81b60' }} />
        </Box>
      ) : !pendingTorrents || pendingTorrents.length === 0 ? (
        <Alert severity="info">暂无待审核种子</Alert>
      ) : (
        <TableContainer component={Paper} sx={{
          borderRadius: 2,
          boxShadow: '0 4px 6px rgba(0,0,0,0.1)',
          overflow: 'hidden'
        }}>
          <Table sx={{ minWidth: 650 }}>
            <TableHead sx={{ backgroundColor: '#e3f2fd' }}>
              <TableRow>
                <TableCell>ID</TableCell>
                <TableCell>名称</TableCell>
                <TableCell>上传者ID</TableCell>
                <TableCell>分类</TableCell>
                <TableCell
                    onClick={() => handleSort('fileSize')}
                    sx={{
                      cursor: 'pointer',
                      '&:hover': { backgroundColor: '#e8eaf6' },
                      display: 'flex',
                      alignItems: 'center',
                      gap: 1
                    }}
                >
                  大小
                  {sortField === 'fileSize' && (
                      <span>{sortDirection === 'asc' ? '↑' : '↓'}</span>
                  )}
                </TableCell>
                <TableCell
                    onClick={() => handleSort('downloads')}
                    sx={{
                      cursor: 'pointer',
                      '&:hover': { backgroundColor: '#e8eaf6' },
                      display: 'flex',
                      alignItems: 'center',
                      gap: 1
                    }}
                >
                  下载量
                  {sortField === 'downloads' && (
                      <span>{sortDirection === 'asc' ? '↑' : '↓'}</span>
                  )}
                </TableCell>                <TableCell>上传时间</TableCell>
                <TableCell>操作</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {pendingTorrents && pendingTorrents
                .filter(torrent =>
                  torrent.fileName?.toLowerCase().includes(searchTerm.toLowerCase()) ||
                  torrent.uploaderId?.toString().includes(searchTerm)
                )
                .map((torrent) => (
                  <TableRow key={torrent.id} hover>
                    <TableCell>{torrent.id}</TableCell>
                    <TableCell>{torrent.fileName}</TableCell>
                    <TableCell>{torrent.uploaderId}</TableCell>
                    <TableCell>{torrent.category || '未分类'}</TableCell>
                    <TableCell>{formatFileSize(torrent.fileSize)}</TableCell>
                    <TableCell>{new Date(torrent.createdAt || torrent.uploadTime).toLocaleString()}</TableCell>
                    <TableCell>
                      <Box sx={{ display: 'flex', gap: 1 }}>
                        <Button
                          variant="outlined"
                          color="success"
                          size="small"
                          startIcon={<CheckCircle />}
                          onClick={() => handleOpenDialog('approve', { ...torrent, name: torrent.fileName })}
                          sx={{ borderRadius: 4 }}
                        >
                          通过
                        </Button>
                        <Button
                          variant="outlined"
                          color="error"
                          size="small"
                          startIcon={<Block />}
                          onClick={() => handleOpenDialog('reject', { ...torrent, name: torrent.fileName })}
                          sx={{ borderRadius: 4 }}
                        >
                          拒绝
                        </Button>
                      </Box>
                    </TableCell>
                  </TableRow>
                ))}
            </TableBody>
          </Table>
        </TableContainer>
      )}
    </Box>
  );

  // 辅助函数：格式化文件大小
  const formatFileSize = (bytes) => {
    if (!bytes || bytes === 0) return '0 Bytes';

    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));

    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  // 促销活动管理视图
  const renderPromotionManagement = () => (
    <Box>
      <Box sx={{ mb: 2, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <Typography variant="h6" sx={{ color: '#8e24aa', fontWeight: 'bold' }}>
          <LocalOffer sx={{ mr: 1, verticalAlign: 'middle' }} />
          促销活动管理
        </Typography>
        
      </Box>

      {!promotions || promotions.length === 0 ? (
        <Alert severity="info">暂无促销活动</Alert>
      ) : (
        <TableContainer component={Paper} sx={{
          borderRadius: 2,
          boxShadow: '0 4px 6px rgba(0,0,0,0.1)',
          overflow: 'hidden'
        }}>
          <Table sx={{ minWidth: 650 }}>
            <TableHead sx={{ backgroundColor: '#f3e5f5' }}>
              <TableRow>
                <TableCell>ID</TableCell>
                <TableCell>种子名称</TableCell>
                <TableCell>开始时间</TableCell>
                <TableCell>结束时间</TableCell>
                <TableCell>操作</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {promotions && promotions.map((promotion) => (
                <TableRow key={promotion.id} hover>
                  <TableCell>{promotion.id}</TableCell>
                  <TableCell>{promotion.fileName || promotion.name || '未知'}</TableCell>
                  <TableCell>{new Date(promotion.promotionStartTime || promotion.startTime).toLocaleString()}</TableCell>
                  <TableCell>{new Date(promotion.promotionEndTime || promotion.endTime).toLocaleString()}</TableCell>
                  <TableCell>
                    <Button
                      variant="outlined"
                      color="error"
                      size="small"
                      startIcon={<Delete />}
                      onClick={() => handleOpenDialog('closePromotion', promotion)}
                      sx={{ borderRadius: 4 }}
                    >
                      结束活动
                    </Button>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </TableContainer>
      )}
    </Box>
  );

  // 举报管理视图
  const renderReportManagement = () => (
    <Box>
      <Box sx={{ mb: 2, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <Typography variant="h6" sx={{ color: '#8e24aa', fontWeight: 'bold' }}>
          <Flag sx={{ mr: 1, verticalAlign: 'middle' }} />
          举报管理
        </Typography>
        <TextField
          placeholder="搜索举报..."
          variant="outlined"
          size="small"
          value={searchTerm}
          onChange={handleSearchChange}
          InputProps={{
            startAdornment: <Search sx={{ color: 'action.active', mr: 1 }} />,
          }}
          sx={{ width: 300 }}
        />
      </Box>

      {!reports || reports.length === 0 ? (
        <Alert severity="info">暂无待处理举报</Alert>
      ) : (
        <TableContainer component={Paper} sx={{
          borderRadius: 2,
          boxShadow: '0 4px 6px rgba(0,0,0,0.1)',
          overflow: 'hidden'
        }}>
          <Table sx={{ minWidth: 650 }}>
            <TableHead sx={{ backgroundColor: '#fff8e1' }}>
              <TableRow>
                <TableCell>ID</TableCell>
                <TableCell>举报者</TableCell>
                <TableCell>被举报内容</TableCell>
                <TableCell>类型</TableCell>
                <TableCell>原因</TableCell>
                <TableCell>提交时间</TableCell>
                <TableCell>状态</TableCell>
                <TableCell>操作</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {reports && reports
                .filter(report =>
                  report.reporterName?.toLowerCase().includes(searchTerm.toLowerCase()) ||
                  report.reason?.toLowerCase().includes(searchTerm.toLowerCase()) ||
                  report.id?.toString().includes(searchTerm)
                )
                .map((report) => (
                  <TableRow key={report.id} hover>
                    <TableCell>{report.id}</TableCell>
                    <TableCell>{report.reporterName || report.reporterId}</TableCell>
                    <TableCell>
                      {report.targetType === 'TORRENT'
                        ? report.torrentName || `种子ID: ${report.torrentId}`
                        : report.commentContent?.substring(0, 30) + '...' || `评论ID: ${report.commentId}`}
                    </TableCell>
                    <TableCell>
                      <Chip
                        label={report.targetType === 'TORRENT' ? '种子' : '评论'}
                        color={report.targetType === 'TORRENT' ? 'primary' : 'secondary'}
                        size="small"
                      />
                    </TableCell>
                    <TableCell>{report.reason}</TableCell>
                    <TableCell>{new Date(report.createTime || report.createdAt).toLocaleString()}</TableCell>
                    <TableCell>
                      <Chip
                        label={report.status === 0 ? '待处理' : '已处理'}
                        color={report.status === 0 ? 'warning' : 'success'}
                        size="small"
                      />
                    </TableCell>
                    <TableCell>
                      {report.status === 0 && (
                        <Button
                          variant="outlined"
                          color="info"
                          size="small"
                          onClick={() => handleOpenDialog('processReport', report)}
                          sx={{ borderRadius: 4 }}
                        >
                          处理
                        </Button>
                      )}
                      {report.status !== 0 && (
                        <Typography variant="body2" color="textSecondary">
                          已处理
                        </Typography>
                      )}
                    </TableCell>
                  </TableRow>
                ))}
            </TableBody>
          </Table>
        </TableContainer>
      )}
    </Box>
  );

  // 通知管理视图
  const renderNoticeManagement = () => (
    <Box>
      <Box sx={{ mb: 2, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <Typography variant="h6" sx={{ color: '#8e24aa', fontWeight: 'bold' }}>
          <Announcement sx={{ mr: 1, verticalAlign: 'middle' }} />
          通知管理
        </Typography>
        <Button
          variant="contained"
          color="secondary"
          startIcon={<AddCircle />}
          onClick={() => handleOpenDialog('createNotice')}
          sx={{
            borderRadius: 4,
            background: 'linear-gradient(45deg, #8e24aa 30%, #d81b60 90%)',
            boxShadow: '0 3px 5px 2px rgba(142, 36, 170, .3)',
          }}
        >
          发布通知
        </Button>
      </Box>

      {!notices || notices.length === 0 ? (
        <Alert severity="info">暂无通知</Alert>
      ) : (
        <TableContainer component={Paper} sx={{
          borderRadius: 2,
          boxShadow: '0 4px 6px rgba(0,0,0,0.1)',
          overflow: 'hidden'
        }}>
          <Table sx={{ minWidth: 650 }}>
            <TableHead sx={{ backgroundColor: '#e8f5e9' }}>
              <TableRow>
                <TableCell>ID</TableCell>
                <TableCell>主题</TableCell>
                <TableCell>内容</TableCell>
                <TableCell>发布时间</TableCell>
                <TableCell>操作</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {notices && notices.map((notice) => (
                <TableRow key={notice.id} hover>
                  <TableCell>{notice.id}</TableCell>
                  <TableCell>{notice.noticeTopic}</TableCell>
                  <TableCell>{notice.content?.substring(0, 50) + (notice.content?.length > 50 ? '...' : '')}</TableCell>
                  <TableCell>{new Date(notice.createTime || notice.createdAt).toLocaleString()}</TableCell>
                  <TableCell>
                    <IconButton 
                      color="error" 
                      size="small"
                      onClick={() => handleOpenDialog('deleteNotice', notice)}
                    >
                      <Delete />
                    </IconButton>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </TableContainer>
      )}
    </Box>
  );

  // 商店管理视图
  const renderStoreManagement = () => (
    <Box>
      <Box sx={{ mb: 2, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <Typography variant="h6" sx={{ color: '#8e24aa', fontWeight: 'bold' }}>
          <Store sx={{ mr: 1, verticalAlign: 'middle' }} />
          商店管理
        </Typography>
        <Button
          variant="contained"
          color="secondary"
          startIcon={<AddCircle />}
          onClick={() => handleOpenDialog('addProduct')}
          sx={{
            borderRadius: 4,
            background: 'linear-gradient(45deg, #8e24aa 30%, #d81b60 90%)',
            boxShadow: '0 3px 5px 2px rgba(142, 36, 170, .3)',
          }}
        >
          添加商品
        </Button>
      </Box>

      {!products || products.length === 0 ? (
        <Alert severity="info">暂无商品</Alert>
      ) : (
        <Grid container spacing={3}>
          {products.map((product) => (
            <Grid item xs={12} sm={6} md={4} key={product.id}>
              <Card sx={{
                height: '100%',
                display: 'flex',
                flexDirection: 'column',
                borderRadius: 3,
                boxShadow: '0 4px 8px rgba(0,0,0,0.1)',
                transition: 'all 0.3s',
                '&:hover': {
                  transform: 'translateY(-5px)',
                  boxShadow: '0 6px 12px rgba(0,0,0,0.15)',
                },
              }}>
                <CardContent sx={{ flexGrow: 1 }}>
                  <Typography variant="h6" gutterBottom sx={{ color: '#8e24aa' }}>
                    {product.name}
                  </Typography>
                  <Typography variant="body2" color="text.secondary" paragraph>
                    {product.description || '无描述'}
                  </Typography>
                  <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mt: 1 }}>
                    <Chip
                      label={product.type}
                      color="primary"
                      size="small"
                      sx={{ borderRadius: 2 }}
                    />
                    <Typography variant="h6" color="error">
                      ¥{product.price}
                    </Typography>
                  </Box>
                  {product.type === 'VIP' && (
                    <Typography variant="body2" sx={{ mt: 1 }}>
                      有效期: {product.duration} 天
                    </Typography>
                  )}
                  {product.stock !== -1 && (
                    <Typography variant="body2" sx={{ mt: 1 }}>
                      库存: {product.stock}
                    </Typography>
                  )}
                </CardContent>
                <CardActions sx={{ p: 2 }}>
                  <Button
                    size="small"
                    color="secondary"
                    onClick={() => handleOpenDialog('editProduct', product)}
                  >
                    编辑
                  </Button>
                  <Button
                    size="small"
                    color="error"
                    onClick={() => handleOpenDialog('deleteProduct', product)}
                  >
                    删除
                  </Button>
                </CardActions>
              </Card>
            </Grid>
          ))}
        </Grid>
      )}
    </Box>
  );

  // 系统设置视图
  const renderSystemSettings = () => (
    <Box>
      <Box sx={{ mb: 2, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <Typography variant="h6" sx={{ color: '#8e24aa', fontWeight: 'bold' }}>
          <Settings sx={{ mr: 1, verticalAlign: 'middle' }} />
          系统设置
        </Typography>
      </Box>

      <Paper elevation={1} sx={{ p: 3, borderRadius: 2 }}>
        <Typography variant="subtitle1" gutterBottom sx={{ color: '#8e24aa', fontWeight: 'bold' }}>
          当前系统参数 (点击参数卡片进行修改)
        </Typography>
        
        <Grid container spacing={3} sx={{ mt: 1 }}>
          {Object.keys(systemParams).length === 0 ? (
            <Grid item xs={12}>
              <Alert severity="info">暂无系统参数</Alert>
            </Grid>
          ) : (
            Object.entries(systemParams).map(([key, value]) => (
              <Grid item xs={12} sm={6} md={4} key={key}>
                <Card 
                  sx={{ 
                    p: 2, 
                    borderRadius: 2, 
                    boxShadow: '0 2px 4px rgba(0,0,0,0.1)',
                    cursor: 'pointer',
                    transition: 'all 0.3s',
                    '&:hover': {
                      transform: 'translateY(-5px)',
                      boxShadow: '0 6px 12px rgba(0,0,0,0.15)',
                      backgroundColor: '#fce4ec',
                    }
                  }}
                  onClick={() => handleOpenDialog('configSystem', { key, value })}
                >
                  <Typography variant="body1" color="text.secondary">
                    {key}
                  </Typography>
                  <Typography variant="h6" sx={{ mt: 1, color: '#8e24aa' }}>
                    {value}
                  </Typography>
                </Card>
              </Grid>
            ))
          )}
        </Grid>
      </Paper>
    </Box>
  );

  // 种子列表视图
  const renderTorrentList = () => (
    <Box>
      <Box sx={{ mb: 2, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <Typography variant="h6" sx={{ color: '#8e24aa', fontWeight: 'bold' }}>
          <List sx={{ mr: 1, verticalAlign: 'middle' }} />
          种子列表
        </Typography>
        <TextField
          placeholder="搜索种子..."
          variant="outlined"
          size="small"
          value={searchTerm}
          onChange={handleSearchChange}
          InputProps={{
            startAdornment: <Search sx={{ color: 'action.active', mr: 1 }} />,
          }}
          sx={{ width: 300 }}
        />
      </Box>

      {allTorrentsLoading ? (
        <Box sx={{ display: 'flex', justifyContent: 'center', p: 3 }}>
          <CircularProgress sx={{ color: '#d81b60' }} />
        </Box>
      ) : !allTorrents || allTorrents.length === 0 ? (
        <Alert severity="info">暂无种子数据</Alert>
      ) : (
        <TableContainer component={Paper} sx={{
          borderRadius: 2,
          boxShadow: '0 4px 6px rgba(0,0,0,0.1)',
          overflow: 'hidden'
        }}>
          <Table sx={{ minWidth: 650 }}>
            <TableHead sx={{ backgroundColor: '#f3e5f5' }}>
              <TableRow>
                <TableCell>ID</TableCell>
                <TableCell>名称</TableCell>
                <TableCell>分类</TableCell>
                <TableCell 
                  onClick={() => handleSort('fileSize')}
                  sx={{ 
                    cursor: 'pointer',
                    '&:hover': { backgroundColor: '#e8eaf6' },
                    whiteSpace: 'nowrap'
                  }}
                >
                  大小
                  {sortField === 'fileSize' && (
                    <span style={{ marginLeft: '4px' }}>{sortDirection === 'asc' ? '↑' : '↓'}</span>
                  )}
                </TableCell>
                <TableCell 
                  onClick={() => handleSort('downloads')}
                  sx={{ 
                    cursor: 'pointer',
                    '&:hover': { backgroundColor: '#e8eaf6' },
                    whiteSpace: 'nowrap'
                  }}
                >
                  下载量
                  {sortField === 'downloads' && (
                    <span style={{ marginLeft: '4px' }}>{sortDirection === 'asc' ? '↑' : '↓'}</span>
                  )}
                </TableCell>
                <TableCell>上传者</TableCell>
                <TableCell>上传时间</TableCell>
                <TableCell>操作</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {getSortedTorrents()
                .filter(torrent =>
                  torrent.fileName?.toLowerCase().includes(searchTerm.toLowerCase()) ||
                  torrent.id?.toString().includes(searchTerm)
                )
                .map((torrent) => (
                  <TableRow key={torrent.id} hover>
                    <TableCell>{torrent.id}</TableCell>
                    <TableCell>{torrent.fileName}</TableCell>
                    <TableCell>{torrent.category || '未分类'}</TableCell>
                    <TableCell>{formatFileSize(torrent.fileSize)}</TableCell>
                    <TableCell>{torrent.downloads || 0}</TableCell>
                    <TableCell>{torrent.uploaderId}</TableCell>
                    <TableCell>{new Date(torrent.updateTime || torrent.createdAt || torrent.uploadTime).toLocaleString()}</TableCell>
                    <TableCell>
                      <Button
                        variant="outlined"
                        color="secondary"
                        size="small"
                        startIcon={<LocalOffer />}
                        onClick={() => handleOpenDialog('createPromotion', torrent)}
                        sx={{ borderRadius: 4 }}
                      >
                        促销
                      </Button>
                    </TableCell>
                  </TableRow>
                ))}
            </TableBody>
          </Table>
        </TableContainer>
      )}
    </Box>
  );

  return (
    <Box>
      <Paper sx={{ mb: 3, borderRadius: 2, overflow: 'hidden' }}>
        <Tabs
          value={tabValue}
          onChange={handleTabChange}
          variant="scrollable"
          scrollButtons="auto"
          sx={{
            background: 'linear-gradient(90deg, #fce4ec 0%, #f3e5f5 100%)',
            '& .Mui-selected': {
              fontWeight: 'bold',
              color: '#d81b60 !important',
            },
            '& .MuiTabs-indicator': {
              backgroundColor: '#d81b60',
            },
          }}
        >
          <Tab icon={<Person />} label="用户管理" />
          <Tab icon={<Movie />} label="种子审核" />
          <Tab icon={<List />} label="种子列表" />
          <Tab icon={<LocalOffer />} label="促销活动" />
          <Tab icon={<Flag />} label="举报管理" />
          <Tab icon={<Announcement />} label="通知管理" />
          <Tab icon={<Store />} label="商店管理" />
          <Tab icon={<Settings />} label="系统设置" />
        </Tabs>
      </Paper>

      {tabValue === 0 && renderUserManagement()}
      {tabValue === 1 && renderTorrentReview()}
      {tabValue === 2 && renderTorrentList()}
      {tabValue === 3 && renderPromotionManagement()}
      {tabValue === 4 && renderReportManagement()}
      {tabValue === 5 && renderNoticeManagement()}
      {tabValue === 6 && renderStoreManagement()}
      {tabValue === 7 && renderSystemSettings()}

      {/* 对话框 */}
      <Dialog open={openDialog} onClose={handleCloseDialog} maxWidth="sm" fullWidth>
        <DialogTitle sx={{ background: 'linear-gradient(45deg, #fce4ec 30%, #f3e5f5 90%)', color: '#8e24aa' }}>
          {dialogType === 'ban' && '封禁用户'}
          {dialogType === 'unban' && '解封用户'}
          {dialogType === 'approve' && '通过种子'}
          {dialogType === 'reject' && '拒绝种子'}
          {dialogType === 'createPromotion' && '创建促销活动'}
          {dialogType === 'closePromotion' && '结束促销活动'}
          {dialogType === 'processReport' && '处理举报'}
          {dialogType === 'createNotice' && '发布通知'}
          {dialogType === 'deleteNotice' && '删除通知'}
          {dialogType === 'addProduct' && '添加商品'}
          {dialogType === 'editProduct' && '编辑商品'}
          {dialogType === 'deleteProduct' && '删除商品'}
          {dialogType === 'configSystem' && '系统参数配置'}
        </DialogTitle>
        <DialogContent sx={{ py: 2 }}>
          {dialogType === 'ban' && (
            <>
              <TextField
                autoFocus
                margin="dense"
                label="封禁原因"
                fullWidth
                multiline
                rows={4}
                value={banReason}
                onChange={(e) => setBanReason(e.target.value)}
                variant="outlined"
                required
                placeholder="请输入封禁用户的原因"
                sx={{ mb: 2 }}
              />
              <FormControl fullWidth variant="outlined">
                <InputLabel>封禁时长</InputLabel>
                <Select
                  value={banTime}
                  onChange={(e) => setBanTime(e.target.value)}
                  label="封禁时长"
                >
                  <MenuItem value={0}>永久封禁</MenuItem>
                  <MenuItem value={1}>1天</MenuItem>
                  <MenuItem value={3}>3天</MenuItem>
                  <MenuItem value={7}>7天</MenuItem>
                  <MenuItem value={14}>14天</MenuItem>
                  <MenuItem value={30}>30天</MenuItem>
                  <MenuItem value={90}>90天</MenuItem>
                  <MenuItem value={180}>180天</MenuItem>
                </Select>
              </FormControl>
            </>
          )}

          {dialogType === 'unban' && (
            <Typography>确定要解封用户 <b>{selectedItem?.username}</b> 吗？</Typography>
          )}

          {dialogType === 'approve' && (
            <Typography>确定要通过种子 <b>{selectedItem?.name}</b> 吗？</Typography>
          )}

          {dialogType === 'reject' && (
            <TextField
              autoFocus
              margin="dense"
              label="拒绝原因"
              fullWidth
              multiline
              rows={4}
              value={reviewReason}
              onChange={(e) => setReviewReason(e.target.value)}
              variant="outlined"
              required
              placeholder="请输入拒绝种子的原因"
            />
          )}

          {dialogType === 'createPromotion' && (
            <>
              <Typography variant="subtitle1" gutterBottom>
                为种子 <b>{selectedItem?.fileName || selectedItem?.name || selectedTorrentId}</b> 创建促销活动
              </Typography>
              <TextField
                margin="dense"
                label="开始时间"
                fullWidth
                type="datetime-local"
                value={startDate}
                onChange={(e) => setStartDate(e.target.value)}
                variant="outlined"
                required
                InputLabelProps={{
                  shrink: true,
                }}
                sx={{ mb: 2 }}
              />
              <TextField
                margin="dense"
                label="结束时间"
                fullWidth
                type="datetime-local"
                value={endDate}
                onChange={(e) => setEndDate(e.target.value)}
                variant="outlined"
                required
                InputLabelProps={{
                  shrink: true,
                }}
              />
            </>
          )}

          {dialogType === 'closePromotion' && (
            <Typography>确定要结束 <b>{selectedItem?.name}</b> 的促销活动吗？</Typography>
          )}

          {dialogType === 'processReport' && (
            <>
              <Box sx={{ mb: 2 }}>
                <Typography variant="subtitle1" gutterBottom>举报详情:</Typography>
                <Typography variant="body2"><strong>举报者:</strong> {selectedItem?.reporterName || selectedItem?.reporterId}</Typography>
                <Typography variant="body2"><strong>举报类型:</strong> {selectedItem?.targetType === 'TORRENT' ? '种子' : '评论'}</Typography>
                <Typography variant="body2"><strong>举报原因:</strong> {selectedItem?.reason}</Typography>
                <Typography variant="body2"><strong>举报时间:</strong> {selectedItem ? new Date(selectedItem.createTime || selectedItem.createdAt).toLocaleString() : ''}</Typography>
                <Divider sx={{ my: 2 }} />
              </Box>
              <TextField
                autoFocus
                margin="dense"
                label="处理结果"
                fullWidth
                multiline
                rows={4}
                value={processResult}
                onChange={(e) => setProcessResult(e.target.value)}
                variant="outlined"
                required
                placeholder="请输入举报处理结果"
                sx={{ mb: 2 }}
              />
              <FormControl fullWidth variant="outlined">
                <InputLabel>处理操作</InputLabel>
                <Select
                  value={actionTaken}
                  onChange={(e) => setActionTaken(e.target.value)}
                  label="处理操作"
                >
                  <MenuItem value={0}>无需操作</MenuItem>
                  <MenuItem value={1}>警告用户</MenuItem>
                  <MenuItem value={2}>删除内容</MenuItem>
                  <MenuItem value={3}>封禁用户</MenuItem>
                </Select>
              </FormControl>
            </>
          )}

          {dialogType === 'createNotice' && (
            <>
              <TextField
                autoFocus
                margin="dense"
                label="通知主题"
                fullWidth
                value={noticeTopic}
                onChange={(e) => setNoticeTopic(e.target.value)}
                variant="outlined"
                required
                placeholder="请输入通知主题"
                sx={{ mb: 2 }}
              />
              <TextField
                margin="dense"
                label="通知内容"
                fullWidth
                multiline
                rows={4}
                value={noticeContent}
                onChange={(e) => setNoticeContent(e.target.value)}
                variant="outlined"
                required
                placeholder="请输入通知内容"
              />
            </>
          )}

          {dialogType === 'deleteNotice' && (
            <Typography>确定要删除通知 <b>{selectedItem?.topic}</b> 吗？</Typography>
          )}

          {(dialogType === 'addProduct' || dialogType === 'editProduct') && (
            <>
              <TextField
                autoFocus
                margin="dense"
                label="商品名称"
                fullWidth
                value={productName}
                onChange={(e) => setProductName(e.target.value)}
                variant="outlined"
                required
                placeholder="请输入商品名称"
                sx={{ mb: 2 }}
              />
              <TextField
                margin="dense"
                label="商品描述"
                fullWidth
                multiline
                rows={2}
                value={productDesc}
                onChange={(e) => setProductDesc(e.target.value)}
                variant="outlined"
                placeholder="请输入商品描述（可选）"
                sx={{ mb: 2 }}
              />
              <TextField
                margin="dense"
                label="价格"
                fullWidth
                type="number"
                value={productPrice}
                onChange={(e) => setProductPrice(e.target.value)}
                variant="outlined"
                required
                InputProps={{
                  startAdornment: <span style={{ marginRight: 8 }}>¥</span>,
                }}
                sx={{ mb: 2 }}
              />
              <FormControl fullWidth variant="outlined" sx={{ mb: 2 }}>
                <InputLabel>商品类型</InputLabel>
                <Select
                  value={productType}
                  onChange={(e) => setProductType(e.target.value)}
                  label="商品类型"
                >
                  <MenuItem value="VIP">VIP会员</MenuItem>
                  <MenuItem value="BONUS">魔力值</MenuItem>
                  <MenuItem value="INVITE">邀请码</MenuItem>
                  <MenuItem value="OTHER">其他商品</MenuItem>
                </Select>
              </FormControl>
              {productType === 'VIP' && (
                <TextField
                  margin="dense"
                  label="有效期（天）"
                  fullWidth
                  type="number"
                  value={productDuration}
                  onChange={(e) => setProductDuration(e.target.value)}
                  variant="outlined"
                  required
                  sx={{ mb: 2 }}
                />
              )}
              <TextField
                margin="dense"
                label="库存数量"
                fullWidth
                type="number"
                value={productStock}
                onChange={(e) => setProductStock(e.target.value)}
                variant="outlined"
                helperText="设为-1表示无限库存"
              />
            </>
          )}

          {dialogType === 'deleteProduct' && (
            <Typography>确定要删除商品 <b>{selectedItem?.name}</b> 吗？</Typography>
          )}

          {dialogType === 'configSystem' && (
            <>
              <TextField
                autoFocus
                margin="dense"
                label="参数键名"
                fullWidth
                value={configKey}
                onChange={(e) => setConfigKey(e.target.value)}
                variant="outlined"
                required
                placeholder="请输入参数键名"
                sx={{ mb: 2 }}
                disabled={!!selectedItem} // 如果是编辑现有参数，禁用键名输入
              />
              <TextField
                margin="dense"
                label="参数值"
                fullWidth
                value={configValue}
                onChange={(e) => setConfigValue(e.target.value)}
                variant="outlined"
                required
                placeholder="请输入参数值"
              />
            </>
          )}
        </DialogContent>
        <DialogActions sx={{ px: 3, pb: 2 }}>
          <Button onClick={handleCloseDialog} color="inherit">
            取消
          </Button>
          <Button 
            onClick={handleAction} 
            variant="contained" 
            color="secondary"
            sx={{
              borderRadius: 4,
              background: 'linear-gradient(45deg, #8e24aa 30%, #d81b60 90%)',
              boxShadow: '0 3px 5px 2px rgba(142, 36, 170, .3)',
            }}
          >
            确认
          </Button>
        </DialogActions>
      </Dialog>

      {/* 提示消息 */}
      <Snackbar
        open={snackbarOpen}
        autoHideDuration={3000}
        onClose={handleSnackbarClose}
        anchorOrigin={{ vertical: 'top', horizontal: 'center' }}
      >
        <Alert onClose={handleSnackbarClose} severity={snackbarSeverity} sx={{ width: '100%' }}>
          {snackbarMessage}
        </Alert>
      </Snackbar>
    </Box>
  );
}

export default Admin; 